package cn.outmaneuver.outman.demo.web.controller;
/**
 * Copyright 2024-2024 by dym. All Rights Reserved.
 */

import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * NginxDemoController
 * <p> </p>
 *
 * @author dym
 * @version 1.0
 * @date 2024/01/15
 */
@RequestMapping("/demo/nginx")
@RestController
public class NginxDemoController {

    private static final Map<String, Integer> NGINX_ADDR_RATE = new ConcurrentHashMap<>();

    @RequestMapping("/test")
    public String testNginx(HttpServletRequest request) throws InterruptedException {
        String sid = request.getParameter("sid");
        long date = new Date().getTime() / 1000;
        String key = sid + "-" + date;
        Thread.sleep(10000L);
        synchronized (key) {
            if (NGINX_ADDR_RATE.containsKey(key)) {
                NGINX_ADDR_RATE.put(key, 1 + NGINX_ADDR_RATE.get(key));
            } else {
                NGINX_ADDR_RATE.put(key, 1);
            }
        }
        return "key:" + key + ",number:" + NGINX_ADDR_RATE.get(key);
    }

    @RequestMapping("/getResult")
    public Map getResult(Integer max,String sid){

        Map<String,Integer> tempMap = new HashMap<>();
        NGINX_ADDR_RATE.forEach((key,value)->{
            if(value>max && key.startsWith(sid)) {
                tempMap.put(key, value);
            }
        });
        return tempMap;
    }
}
